#ifndef _SIG_HPP
#define _SIG_HPP 1
#include <signal.h>

#include "base.hpp"
#include "debug.hpp"
#ifdef PG_DEBUG
#include <iostream>
#endif  // PG_DEBUG

#pragma message "judge if it's a builtin in signal handler"
static pid_t shell;
static void update() { shell = Base::obj().getid(); }
static void trace(int type, pid_t fg) {
#ifdef PG_DEBUG
  std::cout << (type == 0 ? "^z" : "^c") << std::endl;
  std::cout << "Current FG pid : " << fg << std::endl;
  std::cout << "Shell pid : " << shell << std::endl;
#endif  // PG_DEBUG
}
static void NS() {
#if SIG_RUN == 0
  puts("signal process not support now");
#endif
}
/**
 * @brief Handler for ^C
 * signal SIGINT to the fg process
 */
void ACT_SIGINT(int sig) {
  update();
#if SIG_RUN == 1
  if (getpid() == shell) return;
  pid_t fg = tcgetpgrp(STDIN_FILENO);  // get foreground pgid
  trace(1, fg);
  tcsetpgrp(STDIN_FILENO, shell);
  kill(fg, SIGINT);
#else
  NS();
#endif
}
/**
 * @brief Handler for ^Z
 * signal SIGTSTP to the fg process
 */
void ACT_SIGTSTP(int sig) {
  update();
#if SIG_RUN == 1
  if (getpid() == shell) return;
  pid_t fg = tcgetpgrp(STDIN_FILENO);  // get foreground pgid
#if PG_SHUT == 0
  trace(0, fg);
  tcsetpgrp(STDIN_FILENO, shell);
#ifdef PG_DEBUG
  std::cout << "After pgrp set\nNow FG pid : " << tcgetpgrp(STDIN_FILENO)
            << std::endl;
#endif  // PG_DEBUG
  kill(fg, SIGTSTP);
#else
  std::cout << "Current FG pid : " << fg << std::endl;
  std::cout << "Shell pid : " << getpid() << std::endl;
#endif  // PG_SHUT
#else
  NS();
#endif  // SIG_RUN
}
#endif  // header
